﻿@page "/certificateauthorities/{id}/{action}"
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.CertificateAuthorityStore;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;
@layout MainLayout
@inherits Fluxor.Blazor.Web.Components.FluxorLayout
@inject NavigationManager navigationManager
@inject IState<CertificateAuthorityState> certificateAuthorityState
@inject IDispatcher dispatcher

<RadzenBreadCrumb>
    <RadzenBreadCrumbItem Path="/certificateauthorities" Text="@Global.CertificateAuthoritiesTitle" />
    <RadzenBreadCrumbItem Text="@Global.CertificateAuthorityDetailsTitle" />
</RadzenBreadCrumb>

<RadzenText class="mt-3 mb-3" Text="@certificateAuthorityState.Value.CertificateAuthority?.SubjectName" TextStyle="TextStyle.DisplayH3" />

@if (certificateAuthorityState.Value.CertificateAuthority != null)
{
    <div class="mb-1">
        <RadzenBadge Text="@(Enum.GetName(typeof(CertificateAuthoritySources), certificateAuthorityState.Value.CertificateAuthority.Source))" IsPill="true" />
    </div>    
}

<RadzenCardLoader Variant="Variant.Filled" IsLoading=certificateAuthorityState.Value.IsLoading>
    <RadzenTabs Change=@OnChange @bind-SelectedIndex="selectedIndex">
        <Tabs>
            <RadzenTabsItem Text="@Global.Details">
                <CertificateAuthorityDetails></CertificateAuthorityDetails>
            </RadzenTabsItem>
            <RadzenTabsItem Text="@Global.ClientCertificates">
                <CertificateAuthorityClients CertificateAuthority="@certificateAuthorityState.Value?.CertificateAuthority"></CertificateAuthorityClients>
            </RadzenTabsItem>
        </Tabs>
    </RadzenTabs>
</RadzenCardLoader>

@code {
    Dictionary<string, int> mappingActionNameToIndex = new Dictionary<string, int>
    {
        { "details", 0 },
        { "clients", 1 }
    };

    [Parameter]
    public string id { get; set; } = null!;

    [Parameter]
    public string action { get; set; } = null!;

    int selectedIndex = 0;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<SelectRealmSuccessAction>((act) =>
            {
                navigationManager.NavigateTo("/certificateauthorities");
            });
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (string.IsNullOrWhiteSpace(id)) return;
        if (!string.IsNullOrWhiteSpace(action) && mappingActionNameToIndex.ContainsKey(action))
            selectedIndex = mappingActionNameToIndex[action];
        dispatcher.Dispatch(new GetCertificateAuthorityAction { Id = id });
    }

    void OnChange(int index)
    {
        var rec = mappingActionNameToIndex.Single(kvp => kvp.Value == index);
        navigationManager.NavigateTo($"/certificateauthorities/{id}/{rec.Key}");
    }
}